package com.qyhl.webtv.module_circle.circle.friend;

import android.content.Context;
import android.util.Log;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.basiclib.utils.network.model.ApiResult;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleCommentBean;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.service.IntergralService;
import com.qyhl.webtv.module_circle.common.CircleUrl;
import com.qyhl.webtv.module_circle.common.CircleUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/1/23.
 */

public class FriendMomentModel implements FriendMomentContract.FriendModel {
    private FriendMomentPresenter mPresenter;

    @Autowired(name = ServicePathConstant.INTERGRAL_SERICE)
    public IntergralService intergralService;

    public FriendMomentModel(FriendMomentPresenter mPresenter) {
        this.mPresenter = mPresenter;
        ARouter.getInstance().inject(this);
    }

    /**
     * 获取推荐好友列表
     */
    @Override
    public void getRecFriends() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = CircleUrl.CIRCLE_URL + "?timestamp=" + time;
        String userName = CommonUtils.getInstance().getUserName();


        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite() + "&method=newFriends" + "&username=" + userName
                ))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<List<CircleHomeBean.User>>() {
                    @Override
                    public void onError(ApiException e) {
                        mPresenter.setRecError();
                    }

                    @Override
                    public void onSuccess(List<CircleHomeBean.User> users) {
                        if (users != null && users.size() > 0) {
                            mPresenter.setRecFriends(users);
                        } else {
                            mPresenter.setRecError();
                        }
                    }
                });


    }

    /**
     * 获取好友动态列表
     *
     * @param lastId
     */
    @Override
    public void getContent(final String lastId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = CircleUrl.CIRCLE_URL + "?timestamp=" + time;
        String userName = CommonUtils.getInstance().getUserName();
        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite() + "&method=friendTends" + "&username=" + userName + "&lastTopicId=" + lastId
                ))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<List<CircleHomeBean>>() {
                    @Override
                    public void onError(ApiException e) {
                        if ("0".equals(lastId)) {
                            mPresenter.setError(4, CircleUtils.getCircleMessage(e.getCode()));
                        } else {
                            mPresenter.setError(5, CircleUtils.getCircleMessage(e.getCode()));
                        }
                    }

                    @Override
                    public void onSuccess(List<CircleHomeBean> circleHomeBeans) {
                        if (circleHomeBeans!= null && circleHomeBeans.size() > 0) {
                            if ("0".equals(lastId)) {
                                mPresenter.setContent(circleHomeBeans, false);
                            } else {
                                mPresenter.setContent(circleHomeBeans, true);
                            }
                        } else {
                            if ("0".equals(lastId)) {
                                mPresenter.setError(2, "暂无好友动态！");
                            } else {
                                mPresenter.setError(3, "no more");
                            }
                        }
                    }
                });
    }

    /**
     * 关注
     *
     * @param dstUserName
     */
    @Override
    public void doFollow(String dstUserName, final ImageView imageView, final int position) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = CircleUrl.CIRCLE_URL + "?timestamp=" + time;
        String userName = CommonUtils.getInstance().getUserName();
        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite() + "&method=follow" + "&username=" + userName + "&dstUsername=" + dstUserName
                ))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        mPresenter.followError("网络异常，关注失败！", imageView);
                    }

                    @Override
                    public void onSuccess(String s) {
                        ApiResult apiResult = new Gson().fromJson(s,ApiResult.class);
                        if (apiResult.getCode() == 200) {
                            mPresenter.followSuccess(imageView, position);
                        } else {
                            mPresenter.followError(CircleUtils.getCircleMessage(apiResult.getCode()), imageView);
                        }
                    }
                });

    }

    /**
     * 取消关注
     *
     * @param dstUserName
     */
    @Override
    public void undoFollow(String dstUserName, final ImageView imageView, final int position) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = CircleUrl.CIRCLE_URL + "?timestamp=" + time;
        String userName = CommonUtils.getInstance().getUserName();
        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite() + "&method=unfollow" + "&username=" +userName + "&dstUsername=" + dstUserName
                ))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(String s) {
                        ApiResult apiResult = new Gson().fromJson(s,ApiResult.class);
                        if (apiResult.getCode() == 200) {
                            mPresenter.unFollowSuccess(imageView, position);
                        } else {
                            mPresenter.unFollowError(CircleUtils.getCircleMessage(apiResult.getCode()), imageView);
                        }
                    }
                });

    }

    @Override
    public void sendComment(String topicId, String content, final String dstUsername) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        String code = "Z5" + time + "I2863";
        String url = CircleUrl.CIRCLE_URL + "?timestamp=" + time;
        String userName = CommonUtils.getInstance().getUserName();

        EasyHttp.post(url)
                .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite() + "&method=createPost" + "&username=" + userName + "&reply=" + dstUsername
                        + "&topicId=" + topicId + "&content=" + content))
                .isDecrypt(true)
                .decryptKet(code)
                .execute(new SimpleCallBack<CircleCommentBean>() {
                    @Override
                    public void onError(ApiException e) {
                        if (e.getCode() == 155) {
                            mPresenter.commentError("您已经被管理员限制言论！");
                        } else {
                            mPresenter.commentError(CircleUtils.getCircleMessage(e.getCode()));
                        }
                    }

                    @Override
                    public void onSuccess(CircleCommentBean circleCommentBean) {
                        if (StringUtils.isNotEmpty(dstUsername)) {
                            mPresenter.commentSuccess(circleCommentBean.getPostId(), "评论成功！", 1);
                        } else {
                            mPresenter.commentSuccess(circleCommentBean.getPostId(), "评论成功！", 0);
                        }
                    }
                });


    }

    @Override
    public String getCoin(Context context) {
        intergralService.gainCoin("7", "gainCoin",new IntergralService.GainCoinCallBack() {
            @Override
            public void success(CoinBean coinBean) {
                Toasty.normal(context, "成功评论，获得" + coinBean.getCoin() + "金币！").show();
            }

            @Override
            public void error(String msg) {
                Log.i("coin_error", msg);
            }
        });

        return null;
    }
}
